package com.juli.school.service.impl;

import java.util.Map;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.juli.school.dao.entity.UploadRecord;
import com.juli.school.dao.mapper.UploadRecordMapper;
import com.juli.school.utils.core.model.CommonResp;

@Service
public class UploadRecordService {
	
	private final static Logger logger = LoggerFactory.getLogger(UploadRecordService.class);
	
	@Resource
	UploadRecordMapper uploadRecordMapper;
	
	public CommonResp<String> addUploadRecord(UploadRecord uploadRecord){
		CommonResp<String> commonResp = new CommonResp<String>();
		try {
			uploadRecordMapper.insert(uploadRecord);
			commonResp.success();
		} catch (Exception e) {
			logger.error("新增上传记录",e);
			commonResp.exception("新增上传记录异常:"+e.getMessage());
		}
		return commonResp;
	}
	
	public CommonResp<UploadRecord> get(Long id){
		CommonResp<UploadRecord> commonResp = new CommonResp<UploadRecord>();
		try {
			UploadRecord uploadRecord = uploadRecordMapper.get(id);
			commonResp.success();
			commonResp.setData(uploadRecord);
		} catch (Exception e) {
			logger.error("根据主键查询上传记录异常",e);
			commonResp.exception("根据主键查询上传记录异常:"+e.getMessage());
		}
		return commonResp;
	}
	
	/**
	 * @Description: 根据摘要信息获取文件是否已经上传
	 * @author gaoxiang
	 * @date 2017年10月23日 下午6:26:58
	 */
	public CommonResp<String> getByDigest(String digest){
		CommonResp<String> commonResp = new CommonResp<String>();
		try {
			if(Strings.isNullOrEmpty(digest)) {
				commonResp.exception("文件摘要信息不可为空");
				return commonResp;
			}
			UploadRecord uploadRecord = uploadRecordMapper.getByDigest(digest);
			if(uploadRecord == null) {
				commonResp.success();
			} else {
				commonResp.fail();
				Map<String, Object> extraData = Maps.newHashMap();
				extraData.put("picPath", uploadRecord.getPicPath());
				extraData.put("srcPath", uploadRecord.getSrcPath());
				extraData.put("width", uploadRecord.getWidth());
				extraData.put("height", uploadRecord.getHeight());
				commonResp.setExtraData(extraData);
			}
		} catch (Exception e) {
			logger.error("根据摘要查询上传记录异常",e);
			commonResp.exception("根据摘要查询上传记录异常:"+e.getMessage());
		}
		return commonResp;
	}
}
